package com.yulinlin.admin.modules.advice;

import com.netflix.client.ClientException;
import com.yulinlin.admin.modules.exception.ApiException;
import com.yulinlin.common.domain.ResponseVo;
import feign.FeignException;
import feign.RetryableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.nio.file.AccessDeniedException;

@ControllerAdvice
public class ExceptionAdvice {



    @ResponseBody
    @ExceptionHandler(value = RetryableException.class)
    public Object ServiceException(RetryableException ex){
        String message = ex.getMessage();
        return ResponseVo.newInstance(null,400,message);
    }

    @ResponseBody
    @ExceptionHandler(value =ApiException.class)
    public Object ServiceException(ApiException ex){
        String message = ex.getMessage();
        return ResponseVo.newInstance(null,ex.getCode(),message);
    }
    @ExceptionHandler(value = { AccessDeniedException.class })
    public Object noHandlerFoundException(AccessDeniedException ex) {
        return ex.getMessage();
    }

    @ExceptionHandler(value = { NoHandlerFoundException.class })
    public Object noHandlerFoundException(Exception ex) {
        return "404";
    }


    @ResponseBody
    @ExceptionHandler(value = FeignException.class)
    public Object ServiceException(FeignException ex){
        String message = ex.getMessage();
        return ResponseVo.newInstance(null,400,message);
    }



    @ResponseBody
    @ExceptionHandler(value = ClientException.class)
    public Object ServiceException(ClientException ex){
        ex.printStackTrace();
        String message = ex.getMessage();
        return ResponseVo.newInstance(null,400,message);
    }


    @ResponseBody
    @ExceptionHandler(value = ConstraintViolationException.class)
    public Object ServiceException(ConstraintViolationException ex){
        String msg="";
        for (ConstraintViolation<?> constraintViolation : ex.getConstraintViolations()) {
            msg+= constraintViolation.getMessage();
        }
        String message = ex.getMessage();
        return ResponseVo.newInstance(null,400,msg);
    }

    @ResponseBody
    @ExceptionHandler(value = RuntimeException.class)
    public Object ServiceException(RuntimeException ex){
        ex.printStackTrace();
        String message = ex.getMessage();
        if(ex.getCause() instanceof ClientException){
            message = "服务集群异常："+  ex.getCause().getMessage();


        }

        return ResponseVo.newInstance(null,400,message);
    }

}
